﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

namespace VSM
{
    public partial class Popup_LabourCharge : System.Web.UI.Page
    {
        

        private static string Labour = "0";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //dbType = Session[VSM.Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? VSM.Utils.AppConstants.VSM : VSM.Utils.AppConstants.DEALER;
                
                Session["ServiceID"] = Request.QueryString["GeneralID"] == null ? "" : Request.QueryString["GeneralID"];
                getLabourCharge();
                LoadTechnician();
                LoadLabourCharge();
            }
        }

        private void getLabourCharge() {
            string sql = " select DealerCode, DealerName, LabourCharge, UpdatedDate from U_LabourDealer where DealerCode = '" + Session[Utils.AppConstants.ID_Dealer] + "'";
            Services sv = new Services();
            DataTable dt = sv.ExecuteQuery("DEALER", sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                Labour =dt.Rows[0]["LabourCharge"].ToString();

            }
        }

        private void LoadTechnician() {
            Services sv = new Services();
            DataSet dsTechnician = sv.ExecuteQuery("VSM", "select * from [@TECHNICIAN] where U_DealerCode = '" + Session[Utils.AppConstants.ID_Dealer] + "' order by Code ");
            Session["Technician"] = dsTechnician.Tables[0];
        }
        private void LoadLabourCharge() {
            if (Session["ServiceID"].ToString() == "") {
                return;
            }

            Services sv = new Services();
            string sql = "select ROW_NUMBER() OVER(ORDER BY LabourID ASC) AS RowNum, * from U_GeneralServiceLabour gs ";
            sql += " join VSM_ORG..U_FRT frt on frt.FRTID = gs.FRTID where ISNULL(Status, 0) = 0 AND GeneralID = " + Session["ServiceID"].ToString();
         
            Session["dtLabour"] = sv.ExecuteQuery("DEALER", sql).Tables[0];
            gvLabour.DataSource = (DataTable)Session["dtLabour"];
            gvLabour.DataBind();
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                int rowNo = Int32.Parse(lblNo.Text);
                Label lbl_LbID = (Label)row.FindControl("lblLabourID");
                DataTable dtTmp = (DataTable)Session["dtLabour"];
                foreach (DataRow dr in dtTmp.Rows)
                {
                    if (rowNo == Int32.Parse(dr["RowNum"].ToString()))
                    {
                        if (lbl_LbID.Text != "-1")
                        {
                            string sql = "UPDATE U_GeneralServiceLabour set Status = 1 WHERE LabourID = " + lbl_LbID.Text;
                            Services sv = new Services();
                            DataSet ds = new DataSet();
                            DataTable dt = new DataTable();
                            dt.Columns.Add("LabourID");
                            dt.Columns.Add("Status");
                            DataRow drAdd = dt.NewRow();
                            drAdd["LabourID"] = lbl_LbID.Text;
                            drAdd["Status"] = 1;
                            dt.Rows.Add(drAdd);
                            ds.Tables.Add(dt);
                            int count = sv.DeleteGeneralServiceLabour("DEALER", ds);
                            if (count > 0)
                            {
                                dr.Delete();
                                //LoadLabourCharge();
                                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Delete Complete');", true);
                            }
                        }
                        else {
                            dr.Delete();
                            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Delete Complete');", true);
                        }

                        break;
                    }
                }
                //reset number
                dtTmp.AcceptChanges();
                int index = 0;
                foreach (DataRow dr in dtTmp.Rows)
                    dr["RowNum"] = ++index;

                Session["dtLabour"] = dtTmp;
                gvLabour.DataSource = dtTmp;
                gvLabour.DataBind();

            }
            catch (Exception ex)
            {
                //this.lblError.Text = ex.Message;
                //this.lblError.Visible = true;
            }

        }

        protected void txt_Qty_TextChange(object sender, EventArgs e)
        {
            try
            {
                //this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;

                //ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txt_HourCharge");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                double qty = Double.Parse(txtQuantity.Text);
                 double LabourCharge = Double.Parse(Labour) * qty;
                 TextBox txt_LabourCharge = (TextBox)row.FindControl("txt_LabourCharge");
                 txt_LabourCharge.Text = LabourCharge.ToString(); ;
                 saveGrid();
                 gvLabour.DataSource = (DataTable)Session["dtLabour"];
                 gvLabour.DataBind();
                //DataTable tb = (DataTable)Session["dtLabour"];
                //int i = 0;
                //foreach (DataRow dr in tb.Rows) {
                //    if (i == row.RowIndex) {
                //        double qty = Double.Parse(txtQuantity.Text);
                //        double LabourCharge = Double.Parse(Labour) * qty;

                //        dr["Quantity"] = qty;
                //        dr["LabourCharge"] = LabourCharge;
                //    }
                //    i++;
                //}
                //gvLabour.DataSource = tb;
                //gvLabour.DataBind();

                //Session["dtLabour"] = tb;
                //Label lblItemCode = (Label)row.FindControl("lblItemCode");

                //DataTable tb = (DataTable)Session["dtLabour"];
                //if (tb != null)
                //{
                //    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                //    if (rupdate.Length > 0)
                //    {
                //        rupdate[0]["Quantity"] = txtQuantity.Text;
                //        //updateRowTotalPrice(rupdate[0], "Quantity");
                //    }
                //}

                //this.grvPO.EditIndex = -1;

                //BindData(tb);
                //CalcTotal(tb);
            }
            catch (Exception ex)
            {
               // this.lblError.Text = ex.Message;
                //this.lblError.Visible = true;
            }
        }
        protected void TextBox_Change(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            string FRTCode = tb.Text;
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            int rowNo = Int32.Parse(lblNo.Text) - 1;
            int index = 0;

            DataTable dtTmp = (DataTable)Session["dtLabour"];

            foreach (DataRow dr in dtTmp.Rows)
            {
                if (rowNo == index)
                {

                    Services sv = new Services();

                    DataSet dsItem = sv.ExecuteQuery("VSM", "select * from U_FRT where FRTCode like '%" + FRTCode + "%'");

                    if (dsItem.Tables[0].Rows.Count == 1)
                    {
                        dr["FRTID"] = dsItem.Tables[0].Rows[0]["FRTID"];
                        dr["PositionCode"] = dsItem.Tables[0].Rows[0]["FRTCode"];
                        dr["FRTWork"] = dsItem.Tables[0].Rows[0]["FRTWork"]; 
                        dr["Qty"] = 1;
                        dr["Quantity"] = dsItem.Tables[0].Rows[0]["FRTValue"];
                        
                        double lbCharge = Double.Parse(dsItem.Tables[0].Rows[0]["FRTValue"].ToString());
                        dr["HourCharge"] = lbCharge;
                        dr["LabourCharge"] = lbCharge * Double.Parse(Labour);
                        dr["FRTName"] = dsItem.Tables[0].Rows[0]["FRTName"];
                        dr["ActualHour"] = dsItem.Tables[0].Rows[0]["FRTValue"];
                        dr["TechCode"] = "";
                        gvLabour.DataSource = dtTmp;
                        Session["dtLabour"] = dtTmp;
                        gvLabour.DataBind();

                        this.lb_Message.Visible = false;
                        break;
                    }
                    else if (dsItem.Tables[0].Rows.Count > 1)
                    {
                        string msg = "Available parts: ";
                        foreach (DataRow drItem in dsItem.Tables[0].Rows)
                        {
                            msg += drItem["FRTCode"].ToString() + ", ";
                        }
                        this.lb_Message.Text = msg;
                        this.lb_Message.Visible = true;
                        break;
                    }
                    else
                    {
                        this.lb_Message.Text = "There is no job with code [" + FRTCode + "] available";
                        this.lb_Message.Visible = true;
                    }
                }
                index++;
            }
        }

        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = null;// = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        //GetPrice(rupdate[0]);
                    }

                    //this.grvPO.EditIndex = -1;

                    //BindData(tb);
                    //CalcTotal(tb);
                }
            }
            catch (Exception ex)
            {
                this.lb_Message.Text = ex.Message;
                this.lb_Message.Visible = true;
            }
        }

        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            /*
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        updateRowTotalPrice(rupdate[0], "Quantity");
                    }
                }

                //this.grvPO.EditIndex = -1;

                //BindData(tb);
                //CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            */
        }

        protected void txtUnitPrice_OnTextChanged(object sender, EventArgs e)
        {
            /*
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtUnitPrice = (TextBox)row.FindControl("txtUnitPrice");
                if (txtUnitPrice.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtUnitPrice.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["PriceBefDi"] = txtUnitPrice.Text;
                        updateRowTotalPrice(rupdate[0], "PriceBefDi");
                    }
                }

                //this.grvPO.EditIndex = -1;

                //BindData(tb);
                //CalcTotal(tb);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
             * */
        }

        private void saveGrid()
        {
            DataTable dtTmp = (DataTable)Session["dtLabour"];
            dtTmp.Rows.Clear();

            foreach (GridViewRow row in gvLabour.Rows)
            {
                DataRow newRow = dtTmp.NewRow();
                newRow["RowNum"] = ((Label)row.FindControl("lblNo")).Text;
                newRow["LabourID"] = ((Label)row.FindControl("lblLabourID")).Text;
                newRow["PositionCode"] = ((TextBox)row.FindControl("txt_PositionCode")).Text;
                newRow["FRTID"] = ((Label)row.FindControl("txt_FRTID")).Text;
                newRow["FRTName"] = ((Label)row.FindControl("txt_FRTName")).Text;
                newRow["FRTWork"] = ((TextBox)row.FindControl("txt_FRTWork")).Text;
                newRow["Qty"] = ((TextBox)row.FindControl("txt_SubQty")).Text;
                newRow["Quantity"] = ((TextBox)row.FindControl("txt_Qty")).Text;
                newRow["HourCharge"] = ((TextBox)row.FindControl("txt_HourCharge")).Text;
                newRow["LabourCharge"] = ((TextBox)row.FindControl("txt_LabourCharge")).Text;
                newRow["ActualHour"] = ((TextBox)row.FindControl("txt_ActualHour")).Text;
                newRow["TechCode"] = ((DropDownList)row.FindControl("ddl_Technician")).SelectedValue;//((HiddenField)row.FindControl("hf_TechID")).Value;
                dtTmp.Rows.Add(newRow);
            }

            Session["dtLabour"] = dtTmp;
        }

        protected void btn_LabourAdd_Click(object sender, EventArgs e)
        {
            saveGrid();
            DataTable dtTmp = (DataTable)Session["dtLabour"];
            DataRow dr = dtTmp.NewRow();

            dr["LabourID"] = -1;
            dr["PositionCode"] = "";
            dr["FRTWork"] = 0;
            dr["Qty"] = 1;
            dr["Quantity"] = 0;
            dr["HourCharge"] = 0;
            dr["LabourCharge"] = Labour;
            dr["GeneralID"] = Session["ServiceID"];
            dr["RowNum"] = dtTmp.Rows.Count + 1;
            dtTmp.Rows.Add(dr);

            this.gvLabour.DataSource = dtTmp;
            Session["dtLabour"] = dtTmp;
            this.gvLabour.DataBind();
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            saveGrid();
            Services sv = new Services();
            DataSet dsDetail = new DataSet();
            DataTable dtAdd = new DataTable();
            //LabourID
            dtAdd.Columns.Add("LabourID");
            dtAdd.Columns.Add("FRTID");
            dtAdd.Columns.Add("PositionCode");
            dtAdd.Columns.Add("FRTWork");
            dtAdd.Columns.Add("Qty");
            dtAdd.Columns.Add("Quantity");
            dtAdd.Columns.Add("HourCharge");
            dtAdd.Columns.Add("LabourCharge");
            dtAdd.Columns.Add("GeneralID");
            dtAdd.Columns.Add("ActualHour");
            dtAdd.Columns.Add("TechCode");
            DataTable dtTmp = (DataTable)Session["dtLabour"];
            foreach (DataRow dr in dtTmp.Rows)
            {
                
                    dsDetail.Tables.Clear();
                    dtAdd.Rows.Clear();
                    DataRow drAdd = dtAdd.NewRow();
                    drAdd["LabourID"] = dr["LabourID"];
                    drAdd["FRTID"] = dr["FRTID"];
                    drAdd["PositionCode"] = dr["PositionCode"];
                    drAdd["FRTWork"] = dr["FRTWork"];
                    drAdd["Qty"] = dr["Qty"];
                    drAdd["Quantity"] = dr["Quantity"];
                    drAdd["HourCharge"] = dr["HourCharge"];
                    drAdd["LabourCharge"] = dr["LabourCharge"];
                    drAdd["GeneralID"] = Session["ServiceID"];
                    drAdd["ActualHour"] = dr["ActualHour"];
                    drAdd["TechCode"] = dr["TechCode"];
                    dtAdd.Rows.Add(drAdd);
                    dsDetail.Tables.Add(dtAdd);
                    if (drAdd["LabourID"].ToString() == "-1")
                        sv.InsertGeneralServiceLabour("DEALER", dsDetail);
                    else
                        sv.UpdateGeneralServiceLabour("DEALER", dsDetail);
                
                
            }
            LoadLabourCharge();
            this.lb_Message.Text = "Update complete.";
            this.lb_Message.Visible = true;
        }

       

       
        protected void btn_ImportExcel_Click(object sender, EventArgs e)
        {

        }


        protected void gvLabour_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if(e.Row.RowType== DataControlRowType.DataRow){
                HiddenField hf_TechCode = (HiddenField)e.Row.FindControl("hf_TechID");
                DropDownList ddl_Tech = (DropDownList)e.Row.FindControl("ddl_Technician");
                ddl_Tech.DataSource = Session["Technician"];
                ddl_Tech.DataTextField = "Name";
                ddl_Tech.DataValueField = "Code";
                ddl_Tech.DataBind();

                if (hf_TechCode.Value != "") {
                    ddl_Tech.Items.FindByValue(hf_TechCode.Value).Selected = true;
                }
            }
        }
    }
}